
<template>
  <div class="addContainer">
    <div
      style="
        height: 100%;
        padding-left: 150px;
        padding-right: 150px;
        overflow-y: auto;
        padding-bottom: 70px;
      "
    >
      <div style="padding: 20px">
        <el-card>
          <template #header>
            <span style="font-weight: bold; font-size: 16px">编辑采购入库</span>
          </template>
          <div class="addBody">
            <el-form
              ref="formRef"
              :model="formData"
              :rules="formRules"
              label-width="120"
              style="margin-top: 20px"
            >
              <div class="basicInfoContainer">
                <div class="milestone">
                  <div class="milestone-content">基础信息</div>
                </div>
                <div style="margin-top: 40px">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="入库单编号" prop="stockInNo">
                        <el-input
                          v-model="formData.stockInNo"
                          placeholder="请输入"
                          style="width: 300px"
                        >
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="入库单名称" prop="name">
                        <el-input
                          v-model="formData.name"
                          placeholder="请输入"
                          style="width: 300px"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="入库日期" prop="stockInDate">
                        <el-date-picker
                          v-model="formData.stockInDate"
                          style="width: 300px"
                          type="date"
                          placeholder="请选择日期"
                          value-format="YYYY-MM-DD"
                        ></el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="采购单名称" prop="purchaseOrderName">
                        <el-input
                          v-model="formData.purchaseOrderName"
                          placeholder="请输入"
                          style="width: 300px"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="采购单号" prop="purchaseOrderNo">
                        <el-input
                          v-model="formData.purchaseOrderNo"
                          placeholder="请选择成品"
                          style="width: 300px"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="供应商" prop="supplierName">
                        <el-input
                          v-model="formData.supplierName"
                          placeholder="请选择供应商"
                          style="width: 300px"
                        >
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="来料检验名称" prop="inspectionName">
                        <el-input
                          v-model="formData.inspectionName"
                          placeholder="请选择来料检验单"
                          style="width: 300px"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="来料检验单号" prop="inspectionNo">
                        <el-input
                          v-model="formData.inspectionNo"
                          placeholder="请输入"
                          style="width: 300px"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="备注" prop="remark">
                    <el-input
                      v-model="formData.remark"
                      type="textarea"
                      style="width: 795px"
                      :rows="3"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
              <div class="bomContainer">
                <div class="bomInfoContainer">
                  <div class="milestone">
                    <div class="milestone-content">入库明细</div>
                  </div>
                  <div style="margin-top: 40px">
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="物料名称" prop="materialName">
                          <el-input
                            v-model="formData.materialName"
                            placeholder="请输入"
                            style="width: 300px"
                          >
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="物料编号" prop="materialNo">
                          <el-input
                            v-model="formData.materialNo"
                            placeholder="请输入"
                            style="width: 300px"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="规格型号" prop="specification">
                          <el-input
                            v-model="formData.specification"
                            placeholder="请输入"
                            style="width: 300px"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="单位" prop="unit">
                          <el-input
                            v-model="formData.unit"
                            placeholder="请输入"
                            style="width: 300px"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="生产日期" prop="productionDate">
                          <el-date-picker
                            v-model="formData.productionDate"
                            style="width: 300px"
                            type="date"
                            placeholder="请选择日期"
                            value-format="YYYY-MM-DD"
                          ></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="到期日期" prop="expiryDate">
                          <el-date-picker
                            v-model="formData.expiryDate"
                            style="width: 300px"
                            type="date"
                            placeholder="请选择日期"
                            value-format="YYYY-MM-DD"
                          ></el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="批次号" prop="batchNo">
                          <el-input
                            v-model="formData.batchNo"
                            placeholder="请输入"
                            style="width: 300px"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="入库数量" prop="stockInQuantity">
                          <el-input-number
                            v-model="formData.stockInQuantity"
                            placeholder="请输入"
                            style="width: 300px"
                            :min="1"
                            :precision="0"
                          ></el-input-number>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="仓库名称" prop="warehouseName">
                          <el-select
                            v-model="formData.warehouseName"
                            placeholder="请选择仓库名称"
                            style="width: 300px"
                            @change="handleWarehouseChange"
                          >
                            <el-option
                              v-for="item in warehouseOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item
                          label="仓库负责人"
                          prop="warehouseManager"
                        >
                          <el-input
                            v-model="formData.warehouseManager"
                            placeholder="请输入"
                            style="width: 300px"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="库区名称" prop="zoneName">
                          <el-select
                            v-model="formData.zoneName"
                            placeholder="请选择库区"
                            style="width: 300px"
                            @change="handleZoneChange"
                          >
                            <el-option
                              v-for="item in zoneOptions"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="库位名称" prop="locationName">
                          <el-input
                            v-model="formData.locationName"
                            placeholder="请选择库位"
                            style="width: 300px"
                          >
                        
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </el-card>
      </div>
    </div>
    <div class="footer" :class="{ 'footer-visible': isFooterVisible }">
      <div class="footerButton">
        <el-button type="primary" plain style="width: 80px" @click="close"
          >关闭</el-button
        >
        <el-button
          type="primary"
          style="width: 80px"
          @click="submitForm"
          :loading="submitting"
          >确定</el-button
        >
      </div>
    </div>

    <!-- 选择物料对话框 -->
    <MaterialDialog
      v-model="materialDialogVisible"
      @select="handleMaterialSelect"
    />

    <!-- 选择供应商对话框 -->
    <SupplierDialog
      v-model="supplierDialogVisible"
      @select="handleSupplierSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from "vue-router"
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getStockInDetailApi,putStockInUpdateStatusApi } from '@/api/Buy'

const $router = useRouter();
const $route = useRoute();
const formRef = ref<FormInstance>();
const submitting = ref(false);
const materialDialogVisible = ref(false);
const supplierDialogVisible = ref(false);
const stockInId = ref(""); // 存储当前编辑的入库单ID
// 物料选择对话框
const isFooterVisible = ref(false);
// 仓库相关选项
const warehouseOptions = ref([
  { value: "成品仓", label: "成品仓" },
  { value: "原材料仓", label: "原材料仓" },
  { value: "半成品仓", label: "半成品仓" },
]);

const zoneOptions = ref<Array<{ value: string; label: string }>>([]);
const locationOptions = ref<Array<{ value: string; label: string }>>([]);

// 获取入库单详情
const fetchStockInDetail = async () => {
  try {
    const response = await getStockInDetailApi(stockInId.value);
    Object.assign(formData, response);
    // 处理仓库、库区、库位的级联选择
    handleWarehouseChange(response.warehouseName)
    handleZoneChange(response.zoneName)
  } catch (error) {
    ElMessage.error("获取入库单详情失败");
    $router.replace("/storage/entrance/buy");
  }
}

// 提交表单（编辑）
const submitForm = async () => {
  try {
    await formRef.value?.validate();

    submitting.value = true;
    await putStockInUpdateStatusApi({
      id: stockInId.value,
      ...formData,
    });

    ElMessage.success("修改入库单成功");
    $router.replace("/storage/entrance/buy");
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请检查表单");
  } finally {
    submitting.value = false;
  }
};
// 表单数据
const formData = reactive({
  name: "",
  stockInNo: "",
  stockInDate: "",
  purchaseOrderName: "",
  purchaseOrderNo: "",
  supplierName: "",
  supplierNo: "",
  inspectionName: "",
  inspectionNo: "",
  remark: "",

  materialName: "",
  materialNo: "",
  specification: "",
  unit: "",
  productionDate: "",
  expiryDate: "",
  batchNo: "",
  stockInQuantity: 1,
  warehouseName: "",
  zoneName: "",
  locationName: "",
  warehouseManager: "张管理员",
});

// 表单验证规则
const formRules: FormRules = {
  name: [{ required: true, message: '请输入入库单名称', trigger: 'blur' }],
  stockInNo: [{ required: true, message: '请输入入库单编号', trigger: 'blur' }],
  stockInDate: [{ required: true, message: '请选择入库日期', trigger: 'change' }],
  materialName: [{ required: true, message: '请选择物料', trigger: 'blur' }],
  materialNo: [{ required: true, message: '物料编号不能为空', trigger: 'blur' }],
  stockInQuantity: [{ required: true, message: '请输入入库数量', trigger: 'blur' }],
  warehouseName: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  zoneName: [{ required: true, message: '请选择库区', trigger: 'change' }],
  locationName: [{ required: true, message: '请选择库位', trigger: 'change' }]
}


const handleMaterialSelect = (material: any) => {
  formData.materialName = material.name;
  formData.materialNo = material.no;
  formData.specification = material.spec;
  formData.unit = material.unit;
};


const handleSupplierSelect = (supplier: any) => {
  formData.supplierName = supplier.name;
  formData.supplierNo = supplier.no;
};

// 仓库选择变化
const handleWarehouseChange = (val: string) => {
  formData.zoneName = "";
  formData.locationName = "";

  // 模拟根据仓库获取库区
  if (val === "成品仓") {
    zoneOptions.value = [
      { value: "成品A区", label: "成品A区" },
      { value: "成品B区", label: "成品B区" },
    ];
  } else if (val === "原材料仓") {
    zoneOptions.value = [
      { value: "原料A区", label: "原料A区" },
      { value: "原料B区", label: "原料B区" },
    ];
  } else {
    zoneOptions.value = [];
  }
};

// 库区选择变化
const handleZoneChange = (val: string) => {
  formData.locationName = ''
  // 模拟根据库区获取库位
  if (val === "成品A区") {
    locationOptions.value = [
      { value: "A-01-01", label: "A-01-01" },
      { value: "A-01-02", label: "A-01-02" },
    ];
  } else if (val === "成品B区") {
    locationOptions.value = [
      { value: "B-01-01", label: "B-01-01" },
      { value: "B-01-02", label: "B-01-02" },
    ];
  } else {
    locationOptions.value = [];
  }
};

// 关闭页面
const close = () => {
  $router.replace("/storage/entrance/buy");
};

onMounted(() => {
  setTimeout(() => {
    isFooterVisible.value = true;
  }, 100);
  stockInId.value = $route.params.id as string;
  if (!stockInId.value) {
    ElMessage.error("无效的入库单ID");
    $router.replace("/storage/entrance/buy");
    return;
  }
  fetchStockInDetail();
});
</script>

<style scoped lang="scss">
/* 保持原有样式不变 */
.addContainer {
  width: 100%;
  position: relative;
  height: 100%;
  transform: translate(0);

  .addBody {
    width: 100%;

    .basicInfoContainer,
    .bomInfoContainer {
      padding: 20px;

      .milestone {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 1.5px;
        background-color: #dfe2e7;

        .milestone-content {
          border: 1.5px solid #dfe2e7;
          padding: 10px;
          padding-left: 20px;
          padding-right: 20px;
          font-weight: bold;
          font-size: 15px;
          border-radius: 10px;
          z-index: 999;
          background-color: #fff;
          color: #1b9aee;
        }
      }
    }

    .bomInfoContainer {
      margin-top: 20px;
    }
  }

  .footer {
    z-index: 999;
    width: 100%;
    height: 70px;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 10px;
    display: flex;
    justify-content: center;
    box-shadow: 0 -8px 10px rgba(92, 92, 92, 0.1);
    transform: translateY(100%); // 初始状态在视口下方
    transition: transform 0.5s ease-out; // 添加过渡效果

    &.footer-visible {
      transform: translateY(0); // 显示时回到原位
    }
  }
}
</style>